package com.qingyun.web.controller.tiktok;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.security.controller.BaseController;
import com.qingyun.shop.domain.TiktokCoupon;
import com.qingyun.shop.domain.TiktokCouponDraw;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokUserShop;
import com.qingyun.shop.service.ITiktokCouponDrawService;
import com.qingyun.shop.service.ITiktokCouponService;
import com.qingyun.shop.service.ITiktokShopService;
import com.qingyun.tiktok.domain.TiktokVideoSend;
import com.qingyun.tiktok.service.ITiktokVideoSendService;
import com.qingyun.tiktok.webhooks.WebhooksCreateVideo;
import com.qingyun.tiktok.webhooks.WebhooksReceiveMsg;
import com.qingyun.tiktok.webhooks.WebhooksValidate;
import com.qingyun.video.domain.TiktokVideoMerge;
import com.qingyun.video.service.ITiktokVideoMergeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 【请填写功能名称】Controller
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Validated
@Api( tags = {"^平台端 抖音用户管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/webhooks/")
public class TiktokWebhooksController extends BaseController {
	@Autowired
	private ITiktokVideoMergeService videoMergeService;

	@Autowired
	private ITiktokVideoSendService videoSendService;


	@Autowired
	private ITiktokCouponDrawService couponDrawService;

	@Autowired
	private ITiktokShopService shopService;


	@Autowired
	private ITiktokCouponService iTiktokCouponService;

	/**
     * Webhooks地址验证
     */
    @ApiOperation("^Webhooks地址验证")
    @PostMapping("/validate")
	@ResponseBody
    public WebhooksValidate.Content validate(@RequestBody WebhooksValidate webhooksValidate) {
		WebhooksValidate.Content content = webhooksValidate.getContent();
//		String challenge = content.getChallenge();
		String event = webhooksValidate.getEvent();
        return content;
    }

	/**
	 * Webhooks地址验证
	 */
	@ApiOperation("^Webhooks地址验证")
	@PostMapping("/")
	@ResponseBody
	public Object index(@RequestBody String requestJson) {
		JSONObject object = JSON.parseObject(requestJson);
		String event = object.getString("event");
		logger.info("抖音回调开始--------------------------，回调类型={}",event);

		if("verify_webhook".equals(event)){
			WebhooksValidate validate  = JSON.parseObject(requestJson,WebhooksValidate.class);
			return JSON.toJSON(validate.getContent());
		}else if("create_video".equals(event)){
			WebhooksCreateVideo createVideo = JSON.parseObject(requestJson,WebhooksCreateVideo.class);
			String itemId = createVideo.getContent().getItem_id();
			String shareId = createVideo.getContent().getShare_id();
			//更新视频发送状态
			TiktokVideoSend videoSend = videoSendService.getBaseMapper().selectOne(Wrappers.lambdaQuery(TiktokVideoSend.class).eq(TiktokVideoSend::getShareId, shareId));
			videoSend.setItemId(itemId);
			videoSend.setStatus(1);
			videoSendService.updateById(videoSend);
			//更新素材使用状态
			TiktokVideoMerge videoMerge = videoMergeService.getBaseMapper().selectById(videoSend.getMergeId());
			videoMerge.setSendStatus(1);
			videoMergeService.updateById(videoMerge);
			//查询待发送的发送优惠券

			TiktokCouponDraw couponDraw = couponDrawService.selectOneWaitSendByUserId(videoSend.getTiktokUserId());
			if(couponDraw!=null){
				couponDraw.setStatus(1);
				couponDrawService.updateById(couponDraw);
				//减少优惠券库存
				TiktokCoupon tiktokCoupon= iTiktokCouponService.getById(couponDraw.getCouponId());
				tiktokCoupon.setQuantity(tiktokCoupon.getQuantity() - 1);
				iTiktokCouponService.updateById(tiktokCoupon);
				logger.info("优惠券发放成功--------------------------------------");
			}

			//扣除商家额度
			TiktokShop tiktokShop = shopService.getById(videoMerge.getShopId());
			tiktokShop.setVideoCount(tiktokShop.getVideoCount()-1);
			shopService.updateById(tiktokShop);

		}else if("authorize".equals(event)){

		}else if("unauthorize".equals(event)){

		}else if("receive_msg".equals(event)){
			WebhooksReceiveMsg msg = JSON.parseObject(requestJson,WebhooksReceiveMsg.class);
			String content = msg.getContent().getDescription();
			System.out.println(content);
		}else if("enter_im".equals(event)){

		}else if("dial_phone".equals(event)){

		}else if("website_contact".equals(event)){

		}else if("personal_tab_contact".equals(event)){

		}
		return null;
	}



	/**
	 * 分享视频事件
	 */
	@ApiOperation("^分享视频事件")
	@PostMapping("/createVideo")
	@ResponseBody
	public AjaxResult createVideo(@RequestBody WebhooksCreateVideo webhooksCreateVideo) {
		WebhooksCreateVideo.Content content = webhooksCreateVideo.getContent();
		String shareId = content.getShare_id();
		String itemId = content.getItem_id();
		return AjaxResult.success();
	}



}
